package cn.ivicar.app.controller.sae;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

public class ParameterFilter implements Filter {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(ParameterFilter.class);

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		String token = null;
		ServletRequest requestWrapper = null;
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String method = request.getMethod();
		if ("GET".equalsIgnoreCase(method) || "DELET".equalsIgnoreCase(method)) {
			token = (String) request.getParameter("token");
			if (StringUtils.isNotBlank(token)) {
				request.setAttribute("token", token);
				LOGGER.info("request token : " + token);
			}

		} else if ("PUT".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(method)) {
			requestWrapper = new MAPIHttpServletRequestWrapper(request);
			request = (HttpServletRequest) requestWrapper;
			ServletInputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				String params = IOUtils.toString(inputStream);
				JSONObject object = JSONObject.fromObject(params);
				token = object.optString("token", null);
				if (StringUtils.isNotBlank(token)) {
					request.setAttribute("token", token);
					LOGGER.info("request token : " + token);
				}
			}
		}

		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}

}

class MAPIHttpServletRequestWrapper extends HttpServletRequestWrapper {

	private final byte[] body;

	public MAPIHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		body = readBytes(request.getReader(), "utf-8");
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body);
		return new ServletInputStream() {

			@Override
			public int read() throws IOException {
				return bais.read();
			}
		};
	}

	private byte[] readBytes(BufferedReader br, String encoding) throws IOException {
		String str = null, retStr = "";
		while ((str = br.readLine()) != null) {
			retStr += str;
		}
		if (StringUtils.isNotBlank(retStr)) {
			return retStr.getBytes(Charset.forName(encoding));
		}
		return new byte[1];
	}
}
